﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Xml;
using System.Xml.Linq;
using System.Windows.Data;
using System.IO;
using System.Runtime.InteropServices.Automation;

namespace KoRepOnlineSales3
{

    public partial class MainPage : UserControl
    {

        #region Members

        Decimal Amount = 0;
        string ErrMsgStr = "Err Msg";
        List<dsData> list = new List<dsData>();
        List<dsShops> listShops = new List<dsShops>();
        List<dsRegions> listRegions = new List<dsRegions>();
        PagedCollectionView taskListView;
        WebClient wc = new WebClient();
        WebClient wc2 = new WebClient();
        //HttpWebRequest req;
        bool bLockScrollBar1 = false;
        bool IsProcess = false;
        bool IsProcess_Fire_RefreshEvent = false;
        
        int idle_sec = 0;
        System.Windows.Threading.DispatcherTimer myDispatcherTimer = 
            new System.Windows.Threading.DispatcherTimer();

        #endregion

        #region Constructors

        public MainPage()
        {
            InitializeComponent();

            mShops.DataContext = listShops;
            mShops.ItemsSource = listShops;

            mShopsRegions.DataContext = listRegions;
            mShopsRegions.ItemsSource = listRegions;

            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
            wc.AllowReadStreamBuffering = false;
            wc.AllowWriteStreamBuffering = false;
            wc.Headers["Cache-Control"] = "no-cache";
            oDate.SelectedDate = DateTime.Now;

            RefreshGrid();

            myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1000 Milliseconds  
            myDispatcherTimer.Tick += new EventHandler(Each_Tick);
            myDispatcherTimer.Start();
        }

        #endregion Constructors

        #region Common Methods

        public Color HexColor(String hex)
        {
            //remove the # at the front
            hex = hex.Replace("#", "");

            byte a = 255;
            byte r = 255;
            byte g = 255;
            byte b = 255;

            int start = 0;

            //handle ARGB strings (8 characters long)
            if (hex.Length == 8)
            {
                a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                start = 2;
            }

            //convert RGB characters to bytes
            r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
            g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
            b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);

            return Color.FromArgb(a, r, g, b);
        }

        #endregion

        #region Invalidate

        void MyEnabled(bool parEnabled = true)
        {
            oDate.Dispatcher.BeginInvoke(() => oDate.IsEnabled = parEnabled);
            btnGo.Dispatcher.BeginInvoke(() => btnGo.IsEnabled = parEnabled);
            oAutoRefresh.Dispatcher.BeginInvoke(() => oAutoRefresh.IsEnabled = parEnabled);
            txtRefreshInterval.Dispatcher.BeginInvoke(() => txtRefreshInterval.IsEnabled = parEnabled);
            scrollBar1.Dispatcher.BeginInvoke(() => scrollBar1.IsEnabled = parEnabled);

            if (parEnabled == false)
            {
                dataGrid1.Dispatcher.BeginInvoke(() => dataGrid1.Visibility = System.Windows.Visibility.Collapsed);
                txtSecReal.Dispatcher.BeginInvoke(() => txtSecReal.Visibility = System.Windows.Visibility.Collapsed);
                mShops.Dispatcher.BeginInvoke(() => mShops.Visibility = System.Windows.Visibility.Collapsed);
                mShopsRegions.Dispatcher.BeginInvoke(() => mShopsRegions.Visibility = System.Windows.Visibility.Collapsed);
            }
            else
            {
                mShops.Dispatcher.BeginInvoke(() => mShops.Visibility = System.Windows.Visibility.Visible);
                mShopsRegions.Dispatcher.BeginInvoke(() => mShopsRegions.Visibility = System.Windows.Visibility.Visible);
                dataGrid1.Dispatcher.BeginInvoke(() => dataGrid1.Visibility = System.Windows.Visibility.Visible);
                txtSecReal.Dispatcher.BeginInvoke(() => txtSecReal.Visibility = System.Windows.Visibility.Visible);
            }
        }

        void RefreshGrid()
        {
            taskListView = new PagedCollectionView(list);

            dataGrid1.Dispatcher.BeginInvoke(() => dataGrid1.ItemsSource = taskListView);
            lblTotal.Dispatcher.BeginInvoke(() => lblTotal.Text = "Итого : " + Amount.ToString("C"));
            lblTotal.Dispatcher.BeginInvoke(() => lblTotal.Visibility = System.Windows.Visibility.Visible);
            if (!String.IsNullOrEmpty(ErrMsgStr))
            {
                stackPanel_Err.Dispatcher.BeginInvoke(() => stackPanel_Err.Visibility = System.Windows.Visibility.Visible);
                txtBottomErrMsg.Dispatcher.BeginInvoke(() => txtBottomErrMsg.Text = ErrMsgStr);
                txtBottomErrMsg.Dispatcher.BeginInvoke(() => txtBottomErrMsg.Visibility = System.Windows.Visibility.Visible);
            }
            else
            {
                stackPanel_Err.Dispatcher.BeginInvoke(() => stackPanel_Err.Visibility = System.Windows.Visibility.Collapsed);
                txtBottomErrMsg.Dispatcher.BeginInvoke(() => txtBottomErrMsg.Visibility = System.Windows.Visibility.Collapsed);
                txtBottomErrMsg.Dispatcher.BeginInvoke(() => txtBottomErrMsg.Text = "");
            }
        }

        private Exception SetFilter()
        {
            Exception ret = null;
            bool isFind = false;
            List<string> regionsTmp = new List<string>();
            foreach (dsRegions item in mShopsRegions.Items)
            {
                if (item.Checked)
                    regionsTmp.Add(item.Name);
            }


            //foreach (dsShops item in mShops.Items)
            //    item.Checked = false;

            foreach (dsShops item in mShops.Items)
            {
                isFind = false;
                foreach (string s in regionsTmp)
                {
                    if (s == item.Region)
                    {
                        isFind = true;
                        break;
                    }
                }
                if (isFind)
                    item.Checked = true;
                else
                    item.Checked = false;
            }

            mShops.DataContext = null;
            mShops.ItemsSource = null;
            mShops.DataContext = listShops;
            mShops.ItemsSource = listShops;

            Set_GridSet_Row_Selected();

            return ret;
        }

        private void Set_GridSet_Row_Selected()
        {
            dataGrid1.SelectedItems.Clear();
            //dsData selItem = null;
            foreach (dsData item in dataGrid1.ItemsSource)
            {
                if (IsShopCheck(item.ShopName))
                    dataGrid1.SelectedItems.Add(item);
            }
        }

        Boolean IsShopCheck(string ShopName)
        {
            Boolean ret = false;
            int i = 0;
            int count = mShops.Items.Count;
            for (i = 0; i < count; i++)
            {
                dsShops itemShop = (dsShops)mShops.Items[i];
                if (itemShop.Checked == true && ShopName == itemShop.Name)
                {
                    ret = true;
                    break;
                }
            }
            return ret;
        }

        #endregion

        #region Form Events

        public void Each_Tick(object o, EventArgs sender)
        {
            int UpSec = Convert.ToInt32(txtRefreshInterval.Text);
            if (UpSec < 1)
                UpSec = 60;
            else
                UpSec = UpSec * 60;
            
            idle_sec++;
            int dec = idle_sec / 60;
            int dec2 = idle_sec % 60;
            txtSecReal.Text = String.Format("{0},{1:00}", dec, dec2);
            if (idle_sec >= UpSec)
            {
                idle_sec = 0;
                if (oAutoRefresh.IsChecked == true && IsProcess == false)
                    btnGo_Click(null, null);
            }
            else
            {
                if (IsProcess_Fire_RefreshEvent)
                {
                    SetFilter();
                    Set_GridSet_Row_Selected();
                    IsProcess_Fire_RefreshEvent = false;
                }
            }
        }

        // Btn Go
        private void btnGo_Click(object sender, RoutedEventArgs e)
        {
            IsProcess = true;
            ErrMsgStr = "";
            myStoryboard.Begin();
            MyEnabled(false);
            Get();
            //Get2();
        }

        // Shop Region Sel chanched
        private void mShopsRegions_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        // Shop Region Click
        private void ShopCheck_Click(object sender, RoutedEventArgs e)
        {
            SetFilter();
        }

        private void ShopCheck_Checked(object sender, RoutedEventArgs e)
        {
        }

        private void ShopCheck_Click_1(object sender, RoutedEventArgs e)
        {
            Set_GridSet_Row_Selected();
        }

        #region oDate

        private void oDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsProcess == false)
                btnGo_Click(null, null);
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Decimal i = 0;
            foreach (dsData item in dataGrid1.SelectedItems)
            {
                i += (Decimal)item.total;
            }
            string str = "Сумма выбранных - {0} \n(Используйте Ctrl + Click или Shift + Click или Shift + стрелки для выделения строк).";
            txtBottom.Text =
                string.Format(str, i.ToString("C"));
        }

        #endregion

        // Scroll Bar
        private void scrollBar1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (_contentLoaded == false || bLockScrollBar1)
                return;
            if (scrollBar1 != null)
            {
                txtRefreshInterval.Text = scrollBar1.Value.ToString();
            }

        }

        private void txtRefreshInterval_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (bLockScrollBar1)
                return;
            int i = 5;
            bLockScrollBar1 = true;
            try
            {
                i = Convert.ToInt32(txtRefreshInterval.Text);
            }
            catch
            {
                txtRefreshInterval.Text = "5";
                scrollBar1.Value = 5;
                bLockScrollBar1 = false;
                return;
            }
            if(i<1)
                i =1;
            txtRefreshInterval.Text = i.ToString();
            scrollBar1.Value = i;
            bLockScrollBar1 = false;
        }

        #endregion

        #region Data

        #region Get

        void Get()
        {
            wc = new WebClient();

            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);

            wc.AllowReadStreamBuffering = false;
            wc.AllowWriteStreamBuffering = false;
            wc.Headers["Cache-Control"] = "no-cache";

            wc.UseDefaultCredentials = false;
            //wc.Credentials = new NetworkCredential("WebServiceUser", "Password", "APP18");
            wc.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");
            wc.UseDefaultCredentials = false;

            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadMethod);

            Amount = 0;
            list.Clear();
            lblTotal.Text = "-";
            txtBottom.Text = "Идет сбор данных.";
            lblTotal.Visibility = System.Windows.Visibility.Collapsed;
            RefreshGrid();

            DateTime dt = DateTime.Now;
            if (oDate.SelectedDate != null)
                dt = oDate.SelectedDate.Value;

            int Year = dt.Year, Month = dt.Month, Day = dt.Day;
            //string dateStr = String.Format("?dt={0,4:0000}-{1,2:00}-{2,2:00}", Year, Month, Day);
            string dateStr = String.Format("?dt={0,4:0000}-{1,2:00}-{2,2:00}&{3}", Year, Month, Day, Guid.NewGuid().ToString());

            Uri myUri = new Uri(@"http://sp.korablik.local:88/ws/TradeProgressOnline.aspx" + dateStr, UriKind.Absolute);

            wc.DownloadStringAsync(myUri);
        }

        void GetShopsList()
        {
            wc2 = new WebClient();
            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
            wc2.Headers["Cache-Control"] = "no-cache";

            wc2.UseDefaultCredentials = false;
            wc2.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");
            wc2.UseDefaultCredentials = false;

            wc2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadShopsMethod);
            string tmpStr = String.Format("?id={0}", Guid.NewGuid().ToString());
            Uri myUri = new Uri(@"http://sp.korablik.local:88/ws/Catalog/Shops.aspx" + tmpStr, UriKind.Absolute);
            wc2.DownloadStringAsync(myUri);
        }

        //void Get2()
        //{
        //    Amount = 0;
        //    list.Clear();
        //    lblTotal.Text = "-";
        //    txtBottom.Text = "Идет сбор данных.";
        //    lblTotal.Visibility = System.Windows.Visibility.Collapsed;
        //    RefreshGrid();

        //    DateTime dt = DateTime.Now;
        //    if (oDate.SelectedDate != null)
        //        dt = oDate.SelectedDate.Value;
        //    int Year = dt.Year, Month = dt.Month, Day = dt.Day;
        //    // string dateStr = String.Format("?dt={0,4:0000}-{1,2:00}-{2,2:00}", Year, Month, Day);
        //    string dateStr = String.Format("?dt={0,4:0000}-{1,2:00}-{2,2:00}&{3}", Year, Month, Day, Guid.NewGuid().ToString());
        //    Uri myUri = new Uri(@"http://sp.korablik.local:88/ws/ws.aspx" + dateStr);

        //    // "Sat, 19 Jul 2008 19:43:31 GMT"
        //    // req.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToUniversalTime().ToString();

        //    req = (HttpWebRequest)HttpWebRequest.Create(myUri);
        //    req.BeginGetResponse(new AsyncCallback(loadMethod2), null);
        //}

        #endregion

        #region Async methods

        void loadMethod(object sender, DownloadStringCompletedEventArgs e)
        {
            Amount = 0;
            list.Clear();
            lblTotal.Text = "-";
            txtBottom.Text = "Идет сбор данных.";
            lblTotal.Visibility = System.Windows.Visibility.Collapsed;
            RefreshGrid();

            if (e.Error != null)
            {
                MessageBox.Show("Error" + e.Error.Message);
                MyEnabled(true);
                IsProcess = false;
                idle_sec = 0;
                ErrMsgStr = "Ошибка - " + e.Error.Message;
                return;
            }

            try
            {
                XDocument grbs = XDocument.Parse(e.Result);
                var query = from g in grbs.Descendants("tbl")
                            select new
                            {
                                //grbId = (int)g.Element("ID"),
                                grbName = (string)g.Element("ShopName"),
                                grbTill1 = (float)g.Element("Till1"),
                                grbTill2 = (float)g.Element("Till2"),
                                grbTill3 = (float)g.Element("Till3"),
                                grbTill4 = (float)g.Element("Till4"),
                                grbTotal = (float)g.Element("Total")

                            };

                foreach (var grb in query)
                {
                    AddShop(grb.grbName
                        , (float)grb.grbTill1
                        , (float)grb.grbTill2
                        , (float)grb.grbTill3
                        , (float)grb.grbTill4
                        , (float)grb.grbTotal);
                }
            }
            catch (Exception err)
            {
                ErrMsgStr = err.Message;
            }

            if (Log.Items.Count > 500000)
                Log.Items.RemoveAt(0);

            string LogMsg = 
                DateTime.Now.ToShortDateString()
                + " ; " + DateTime.Now.ToShortTimeString()
                + @" >>> " + oDate.SelectedDate.Value.ToShortDateString() + @" >>> "
                + " ; Итого - " + Amount.ToString("C");

            Log.Items.Add(LogMsg);

            GetShopsList();
        }

        //private void loadMethod2(IAsyncResult ar)
        //{
        //    if (ar.IsCompleted)
        //    {
        //        try
        //        {
        //            HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(ar);
        //            Stream stream = resp.GetResponseStream();
        //            StreamReader sr = new StreamReader(stream);
        //            string res = sr.ReadToEnd();
        //            sr.Close();
        //            string str = res.ToString();

        //            XDocument grbs = XDocument.Parse(str);
        //            var query = from g in grbs.Descendants("tbl")
        //                        select new
        //                        {
        //                            //grbId = (int)g.Element("ID"),
        //                            grbName = (string)g.Element("ShopName"),
        //                            grbTill1 = (float)g.Element("Till1"),
        //                            grbTill2 = (float)g.Element("Till2"),
        //                            grbTill3 = (float)g.Element("Till3"),
        //                            grbTill4 = (float)g.Element("Till4"),
        //                            grbTotal = (float)g.Element("Total")

        //                        };

        //            foreach (var grb in query)
        //            {
        //                AddShop(grb.grbName
        //                    , (float)grb.grbTill1
        //                    , (float)grb.grbTill2
        //                    , (float)grb.grbTill3
        //                    , (float)grb.grbTill4
        //                    , (float)grb.grbTotal);
        //            }
        //        }
        //        catch (Exception err)
        //        {
        //            ErrMsgStr = err.Message;
        //        }

        //        RefreshGrid();
        //        MyEnabled(true);
        //    }
        //    idle_sec = 0;
        //    IsProcess = false;
        //}

        void loadShopsMethod(object sender, DownloadStringCompletedEventArgs e)
        {
            Exception ex = null;
            if (e.Error != null)
            {
                ex = e.Error;
                MessageBox.Show("Error" + e.Error.Message);
                return;
            }

            try
            {
                XDocument grbs = XDocument.Parse(e.Result);
                var query = from g in grbs.Descendants("tbl")
                            select new
                            {
                                //grbId = (int)g.Element("ID"),
                                grbId = (int)g.Element("ID"),
                                grbName = (string)g.Element("Name"),
                                grbRegion = (string)g.Element("Region"),

                            };

                foreach (var grb in query)
                {
                    if (grb.grbRegion != null)
                        AddShopNameToList((int)grb.grbId, (string)grb.grbName, (string)grb.grbRegion.Trim());
                }
            }
            catch (Exception err)
            {
                ex = err;
                ErrMsgStr = err.Message;
            }

            // Sort List Shops
            listShops.Sort(delegate(dsShops o1, dsShops o2) { return o1.Name.CompareTo(o2.Name); });

            // Sort List Regions
            listRegions.Sort(delegate(dsRegions o1, dsRegions o2) { return o1.Name.CompareTo(o2.Name); });

            RefreshGrid();
            MyEnabled(true);
            idle_sec = 0;
            IsProcess = false;
            IsProcess_Fire_RefreshEvent = true;
        }

        #endregion

        #region Fill Lists

        void AddShop(String mStr, float til1, float til2, float til3, float til4, float total)
        {
            bool isFind = false;
            foreach (dsData item in list)
            {
                if (item.ShopName == mStr)
                {
                    isFind = true;
                    break;
                }
            }

            if (isFind == false)
            {
                dsData newDataRecord;
                newDataRecord = new dsData();
                newDataRecord.ShopName = mStr;
                newDataRecord.kassa1 = til1;
                newDataRecord.kassa2 = til2;
                newDataRecord.kassa3 = til3;
                newDataRecord.kassa4 = til4;
                newDataRecord.total = total;
                Amount += (Decimal)total;
                list.Add(newDataRecord);
            }
        }
        
        void AddShopNameToList(int mId, string mName, string mRegion)
        {
            if (FindShopInList(mName) == false)
            {
                dsShops newR = new dsShops(mId, mName, mRegion, true);
                listShops.Add(newR);
                AddRegionNameToList(mRegion);
            }
        }

        bool FindShopInList(string ShopName)
        {
            bool ret = false;
            foreach (dsShops item in listShops)
            {
                if (item.Name == ShopName)
                {
                    ret = true;
                    break;
                }
            }
            return ret;
        }

        void AddRegionNameToList(string mName)
        {
            bool isFind = false;
            foreach (dsRegions item in listRegions)
            {
                if (item.Name == mName)
                {
                    isFind = true;
                    break;
                }
            }
            if(isFind==false)
            {
                dsRegions newR = new dsRegions(mName, true);
                listRegions.Add(newR);
            }
        }

        #endregion        

        #endregion

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            object[,] myArray = new object[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
            ExportToExcelTools.ExportToExcel((object[,])myArray);
        }
    }

    #region Data class

    public class dsData
    {
        public int id { get; set; }
        private string _ShopName = "";
        public string ShopName
        {
            get { return _ShopName; }
            set
            {
                if (value == "Алтуфьево Белозёрская")
                    _ShopName = "Алтуфьево Белозерская";
                else if (value == "Орехово 2")
                    _ShopName = "Орехово-2";
                else if (value == "Разумовская")
                    _ShopName = "Петровско-Разумовская";
                else if (value == "Речной вокзал")
                    _ShopName = "Речной Вокзал";
                else if (value == "Рязань 2")
                    _ShopName = "Рязань-2";
                else if (value == "Сергиев Посад")
                    _ShopName = "Сергиев-Посад";
                else if (value == "Тропарёво")
                    _ShopName = "Тропарево";
                else
                    _ShopName = value;
            }
        }
        public float kassa1 { get; set; }
        public float kassa2 { get; set; }
        public float kassa3 { get; set; }
        public float kassa4 { get; set; }
        public float total { get; set; }
    }

    public class dsShops
    {
        public dsShops() { }
        public dsShops(int mID, string mName, string mRegion, bool mChecked)
        {
            this.Id = mID;

            if (mName == "Алтуфьево Белозёрская")
                _Name = "Алтуфьево Белозерская";
            else if (mName == "Орехово 2")
                _Name = "Орехово-2";
            else if (mName == "Разумовская")
                _Name = "Петровско-Разумовская";
            else if (mName == "Речной вокзал")
                _Name = "Речной Вокзал";
            else if (mName == "Рязань 2")
                _Name = "Рязань-2";
            else if (mName == "Сергиев Посад")
                _Name = "Сергиев-Посад";
            else if (mName == "Тропарёво")
                _Name = "Тропарево";
            else
                _Name = mName;

            this.Region = mRegion;
            this.Checked = mChecked;
        }

        public int Id { get; set; }
        private string _Name = "";
        public string Name
        {
            get{ return _Name;}
            set
            {
                if (value == "Алтуфьево Белозёрская")
                    _Name = "Алтуфьево Белозерская";
                else if (value == "Орехово 2")
                    _Name = "Орехово-2";
                else if (value == "Разумовская")
                    _Name = "Петровско-Разумовская";
                else if (value == "Речной вокзал")
                    _Name = "Речной Вокзал";
                else if (value == "Рязань 2")
                    _Name = "Рязань-2";
                else if (value == "Сергиев Посад")
                    _Name = "Сергиев-Посад";
                else if (value == "Тропарёво")
                    _Name = "Тропарево";
                else
                    _Name = value;
            }
        }
        public string Region { get; set; }
        public Boolean Checked { get; set; }
    }

    public class dsRegions
    {
        public dsRegions() { }
        public dsRegions(string mName, bool mChecked)
        {
            this.Name = mName;
            this.Checked = mChecked;
        }

        public string Name { get; set; }
        public Boolean Checked { get; set; }
    }

    #endregion

}
